/**
 * https://leetcode.cn/submissions/detail/562835373/
 *213. 打家劫舍 II
 *Medium 黄伟杰 2024.9.8
 *线性DP
 */

#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
    int rob(vector<int> &nums)
    {
        int n = nums.size();
        if (n == 1)
            return nums[0];
        if (n == 3)
            return max(nums[0], max(nums[1], nums[2]));
        int ans = 0;
        vector<int> dp1(n, 0);
        vector<int> dp2(n, 0);
        dp1[0] = nums[0];
        dp1[1] = max(nums[0], nums[1]);
        dp2[0] = nums[n - 1];
        dp2[1] = max(nums[n - 1], nums[0]);
        for (int i = 2; i < n - 1; i++)
        {
            dp1[i] = max(dp1[i - 2] + nums[i], dp1[i - 1]);
        }
        for (int i = 2; i < n - 1; i++)
            dp2[i] = max(dp2[i - 2] + nums[i - 1], dp2[i - 1]);
        return max(dp1[n - 2], dp2[n - 2]);
    }
};